package com.carbon.assets.controller;

import com.carbon.assets.common.BaseController;
import com.carbon.assets.entity.CarbonMethodologyContent;
import com.carbon.assets.param.CarbonMethodologyQueryParam;
import com.carbon.assets.repository.MethodologyRepository;
import com.carbon.domain.common.ApiResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 碳减排方法学es搜索控制器
 * </p>
 *
 * @author cbd
 * @since 2021-07-31
 */
@Slf4j
@RestController
@RequestMapping("/EscarbonMethodology")
@Api(value = "碳减排方法学模块es搜索", tags = {"碳减排方法学ES模块"})
public class CarbonMethodologyEsController extends BaseController {

    @Autowired
    private MethodologyRepository methodologyRepository;
    @PostMapping("/getByKeyword")
    @ApiOperation(value = "方法学全文检索列表",notes = "方法学全文检索列表")
    public ApiResult<Map<String, Object>> findByKeyword(@RequestBody(required = false) Map<String, Object> params)
    {
        try {
            log.info("方法学搜索请求: {}", params);
            
            // 将Map参数转换为CarbonMethodologyQueryParam
            CarbonMethodologyQueryParam carbonMethodologyQueryParam = new CarbonMethodologyQueryParam();
            
            if (params != null) {
                carbonMethodologyQueryParam.setSearchKey((String) params.get("searchKey"));
                carbonMethodologyQueryParam.setStatusCode((String) params.get("statusCode"));
                carbonMethodologyQueryParam.setFieldCode((String) params.get("fieldCode"));
                carbonMethodologyQueryParam.setIndustryCode((String) params.get("industryCode"));
                
                // 处理certificationCriteria字段类型转换
                Object certCriteria = params.get("certificationCriteria");
                if (certCriteria != null) {
                    if (certCriteria instanceof String) {
                        try {
                            carbonMethodologyQueryParam.setCertificationCriteria(Integer.parseInt((String) certCriteria));
                        } catch (NumberFormatException e) {
                            log.warn("certificationCriteria转换失败: {}", certCriteria);
                        }
                    } else if (certCriteria instanceof Integer) {
                        carbonMethodologyQueryParam.setCertificationCriteria((Integer) certCriteria);
                    }
                }
                
                // 设置分页参数
                Object current = params.get("current");
                Object size = params.get("size");
                if (current != null) {
                    carbonMethodologyQueryParam.setCurrent(Integer.parseInt(current.toString()));
                } else {
                    carbonMethodologyQueryParam.setCurrent(1);
                }
                if (size != null) {
                    carbonMethodologyQueryParam.setSize(Integer.parseInt(size.toString()));
                } else {
                    carbonMethodologyQueryParam.setSize(10);
                }
            } else {
                carbonMethodologyQueryParam.setCurrent(1);
                carbonMethodologyQueryParam.setSize(10);
            }
            
            // 调用实际的搜索逻辑
            return findByKeyword2(carbonMethodologyQueryParam);
            
        } catch (Exception e) {
            log.error("方法学搜索异常", e);
            return ApiResult.fail("系统异常: " + e.getMessage());
        }
    }

    @PostMapping("/getByKeyword2")
    @ApiOperation(value = "方法学全文检索列表",notes = "方法学全文检索列表")
    public ApiResult<Map<String, Object>> findByKeyword2(@Valid @RequestBody(required = false) CarbonMethodologyQueryParam carbonMethodologyQueryParam)
    {
        try {
            log.info("方法学搜索参数: {}", carbonMethodologyQueryParam);
            
            // 确保分页参数不为空
            if (carbonMethodologyQueryParam.getCurrent() == null) {
                carbonMethodologyQueryParam.setCurrent(1);
            }
            if (carbonMethodologyQueryParam.getSize() == null) {
                carbonMethodologyQueryParam.setSize(10);
            }
            
            Page<CarbonMethodologyContent> methodologies;
            
            if(carbonMethodologyQueryParam.getSearchKey() != null && !carbonMethodologyQueryParam.getSearchKey().trim().isEmpty())
            {
                String content = carbonMethodologyQueryParam.getSearchKey();
                String name = carbonMethodologyQueryParam.getSearchKey();
                String industryCodeName = carbonMethodologyQueryParam.getSearchKey();
                String dictCode = carbonMethodologyQueryParam.getSearchKey();
                methodologies = methodologyRepository.
                        findByNameOrContentOrIndustryCodeNameOrDictCode(content, name, industryCodeName, dictCode, PageRequest.of(0, 10000));
            } else {
                methodologies = methodologyRepository.
                        findAll(PageRequest.of(carbonMethodologyQueryParam.getCurrent()-1, carbonMethodologyQueryParam.getSize()));
            }
            
            log.info("查询到的方法学数量: {}", methodologies.getTotalElements());
            return ApiResult.ok(getSearchResMap(methodologies, carbonMethodologyQueryParam));
            
        } catch (Exception e) {
            log.error("方法学搜索异常", e);
            return ApiResult.fail("系统异常: " + e.getMessage());
        }
    }

    Map<String, Object> getSearchResMap(Page<CarbonMethodologyContent> methodologies, CarbonMethodologyQueryParam carbonMethodologyQueryParam)
    {
        try {
            log.info("开始处理搜索结果，总数: {}", methodologies.getTotalElements());
            
            List<CarbonMethodologyContent> methodList = new ArrayList<>();
            
            // 处理核证标准字段
            String certificationCriteria = null;
            if (carbonMethodologyQueryParam.getCertificationCriteria() != null) {
                certificationCriteria = "00" + carbonMethodologyQueryParam.getCertificationCriteria().toString();
            }
            
            String fieldCode = carbonMethodologyQueryParam.getFieldCode();
            String industryCode = carbonMethodologyQueryParam.getIndustryCode();
            String statusCode = carbonMethodologyQueryParam.getStatusCode();
            
            log.info("过滤条件 - certificationCriteria: {}, fieldCode: {}, industryCode: {}, statusCode: {}", 
                    certificationCriteria, fieldCode, industryCode, statusCode);
            
            // 应用过滤条件
            if (certificationCriteria != null || fieldCode != null || industryCode != null || statusCode != null) {
                for (CarbonMethodologyContent carbonMethodologyContent : methodologies.getContent()) {
                    if (Match(certificationCriteria, fieldCode, industryCode, statusCode, carbonMethodologyContent) == 1) {
                        carbonMethodologyContent.setContent("");
                        methodList.add(carbonMethodologyContent);
                    }
                }
            } else {
                for (CarbonMethodologyContent carbonMethodologyContent : methodologies.getContent()) {
                    carbonMethodologyContent.setContent("");
                    methodList.add(carbonMethodologyContent);
                }
            }
            
            log.info("过滤后的方法学数量: {}", methodList.size());
            
            // 分页处理
            List<CarbonMethodologyContent> resList = new ArrayList<>();
            int startNum = (carbonMethodologyQueryParam.getCurrent() - 1) * carbonMethodologyQueryParam.getSize().intValue();
            int endNum = Math.min(startNum + carbonMethodologyQueryParam.getSize().intValue(), methodList.size());
            
            for (int i = startNum; i < endNum; i++) {
                if (i < methodList.size()) {
                    resList.add(methodList.get(i));
                }
            }
            
            Map<String, Object> res = new HashMap<>();
            res.put("current", carbonMethodologyQueryParam.getCurrent());
            res.put("total", methodList.size());
            res.put("data", resList);
            
            log.info("最终返回数据 - current: {}, total: {}, dataSize: {}", 
                    carbonMethodologyQueryParam.getCurrent(), methodList.size(), resList.size());
            
            return res;
            
        } catch (Exception e) {
            log.error("处理搜索结果异常", e);
            Map<String, Object> errorRes = new HashMap<>();
            errorRes.put("current", 1);
            errorRes.put("total", 0);
            errorRes.put("data", new ArrayList<>());
            return errorRes;
        }
    }

    public int Match(String certificationCriteria, String fieldCode, String industryCode, String statusCode, CarbonMethodologyContent carbonMethodologyContent)
    {
        try {
            if (certificationCriteria != null && carbonMethodologyContent.getCertificationCriteria() != null 
                && !carbonMethodologyContent.getCertificationCriteria().equals(certificationCriteria)) {
                return 0;
            }
            if (fieldCode != null && carbonMethodologyContent.getFieldCode() != null 
                && !carbonMethodologyContent.getFieldCode().equals(fieldCode)) {
                return 0;
            }
            if (industryCode != null && carbonMethodologyContent.getIndustryCode() != null 
                && !carbonMethodologyContent.getIndustryCode().equals(industryCode)) {
                return 0;
            }
            if (statusCode != null && carbonMethodologyContent.getStatusCode() != null 
                && !carbonMethodologyContent.getStatusCode().equals(statusCode)) {
                return 0;
            }
            return 1;
        } catch (Exception e) {
            log.warn("匹配方法学时发生异常: {}", e.getMessage());
            return 0;
        }
    }
}

